<template>
  <div class="employees-container">
    <div class="app-container">
      <el-card shadow="always" :body-style="{ padding: '20px' }">
        <div slot="header">
          <PageTools>
            <!-- 插入到left插槽位置 -->
            <template #left>
              <span>总记录数：{{ total }}</span>
            </template>
            <!-- 插入到right插槽位置 -->
            <template #right>
              <el-button v-if="checkPoints('aa')" type="warning" size="small" @click="$router.push('/import')">导入excel</el-button>
              <el-button v-if="checkPoints('aa')" type="danger" size="small" @click="exportExcel">导出excel</el-button>
              <el-button v-if="checkPoints('asd')" type="primary" size="small" @click="addtheEmployee()">新增员工</el-button>
            </template>
          </PageTools>
        </div>
        <div>
          <!-- table列表 -->
          <el-table border :data="employees" :default-sort="{prop:'workNumber'}">
            <el-table-column type="index" label="序号" />
            <el-table-column prop="username" label="姓名" />
            <!-- 员工头像 -->

            <el-table-column label="头像">
              <template #default="{row}">
                <el-image class="staff" :src="row.staffPhoto" fit="fill" @click.native="toShowQCcode(row)">

                </el-image>
              </template>
            </el-table-column>

            <el-table-column prop="workNumber" label="工号" />
            <el-table-column prop="formOfEmployment" label="聘用形式">
              <template #default="{row}">
                {{ formatEmployment(row.formOfEmployment) }}
              </template>
            </el-table-column>
            <el-table-column prop="departmentName" label="部门" />
            <el-table-column label="入职时间" sortable prop="timeOfEntry" />
            <el-table-column label="账户状态">
              <el-switch v-model="qy" />
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="280">
              <template #default="{row}">
                <el-button type="text" size="small" @click="$router.push('/employees/detail/'+row.id)">查看</el-button>
                <el-button type="text" size="small" @click="setPermission(row)">分配角色</el-button>
                <el-button type="text" size="small" @click="delEmployees(row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页组件 -->
          <el-row
            type="flex"
            justify="center"
            align="middle"
            style="height: 60px"
          >
            <el-pagination
              :total="total"
              :current-page="pages.page"
              :page-size="pages.size"
              :page-sizes="[2, 5, 10, 20]"
              layout="prev, pager, next,sizes"
              @current-change="changePage"
              @size-change="sizeChange"
            />
          </el-row>
        </div>
      </el-card>
    </div>
    <add-employee :is-show-dialog.sync="isShowDialog"></add-employee>
    <!-- 在这个里添加一个弹出层组件,并且可以显示二维码  (组件里qccode的加载时机有问题 在mounted中会报错)-->
    <!-- <PhotoQCcode :is-show-q-ccode.sync="isShowQCcode" :employees="employees" /> -->

    <!-- 二维码弹出层 -->
    <el-dialog
      title="扫码加好友"
      :visible.sync="isShowQCcode"
      width="30%"
    >
      <el-row type="flex" justify="center">

        <canvas ref="cav" />

      </el-row>

    </el-dialog>

    <!-- 权限控制弹出层 -->
    <UserContrail ref="arole" :show-permission-dialog.sync="showPermissionDialog" />
  </div>
</template>
<script>
import QrCode from 'qrcode'
import addEmployee from '@/views/employees/components/add-employee'
import EmployeeEnum from '@/api/constant/employees'
import { getEmployeesListAPI, delEmployeeAPI } from '@/api/employees'
import UserContrail from '@/views/setting/components/userContrail.vue'
export default {
  components: {
    addEmployee,
    UserContrail

  },
  data () {
    return {

      showPermissionDialog: false, // 控制权限管理弹出层的显示和隐藏

      qy: true,
      employees: [], // 员工列表信息
      pages: {
        page: 1, // 页码
        size: 2 // 每页显示条数
      },
      total: 0, // 数据总数
      isShowDialog: false, // 控制弹出层的显示和隐藏
      isShowQCcode: false // 控制二维码弹出层的显示和隐藏
    }
  }, created() {
    console.log(EmployeeEnum.hireType)
    this.getEmployeesList()
  },
  methods: {
    // 切换每页显示的数据
    sizeChange(size) {
      console.log(size)
      this.pages.size = size
      this.getEmployeesList()
    },
    // 分配角色按钮
    setPermission(row) {
      this.showPermissionDialog = true

      this.$refs.arole.getUserDetailById(row.id)
    },

    // 点击头像显示二维码
    toShowQCcode(row) {
      console.log(row)
      if (row.staffPhoto) {
        this.isShowQCcode = true
        this.$nextTick(() => {
        // 弹出层只有弹出之后才可以获取到dom
          QrCode.toCanvas(this.$refs.cav, row.staffPhoto)
        })
      }
    },

    // 调用获取员工列表的API
    async getEmployeesList() {
      const data = await getEmployeesListAPI(this.pages)
      // console.table(data.rows)
      this.employees = data.rows
      console.log(this.employees)
      this.total = data.total
    },
    // 切换页码的方法
    changePage(page) {
      this.pages.page = page
      this.getEmployeesList()
    },
    // 对聘用形式进行格式化(1是正式,2是非正式)
    formatEmployment(type) {
      // 对元数据进行处理后,返回经过处理的数据(把数组转化为对象)
      const hireType = EmployeeEnum.hireType
      const map = {}
      hireType.forEach(item => {
        map[item.id] = item.value
      })
      return map[type]
    },
    // 删除员工
    delEmployees(id) {
      this.$confirm('确认删除吗', '提示').then(async() => {
        await delEmployeeAPI(id)
        // 下面写法也可
        //  const newTotal = Math.ceil(this.total ) / this.pages.size // 获取到总页码数量

        const newTotal = Math.ceil((this.total - 1) / this.pages.size) // 获取到总页码数量
        if (newTotal > 0) {
          this.pages.page = this.pages.page > newTotal ? newTotal : this.pages.page
        }
        this.$message.success('删除成功')
        this.getEmployeesList()
      }).catch(console.log)
    },
    // 新增员工
    addtheEmployee() {
      this.isShowDialog = true
    },
    // 导出数据以excel的形式
    async exportExcel() {
      // 按需导入js模块
      const excel = await import('@/utils/Export2Excel')
      // console.log(excel)
      const ships = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '工号': 'workNumber',
        '转正日期': 'correctionTime',
        '部门': 'departmentName'
      }
      const header = Object.keys(ships) // ['姓名', '年龄', '工资']
      const data = this.transformExcelData(this.employees, Object.values(ships)) // this.employees是对象的形式,需要转换成2唯数组
      // data
      // [
      //   ['刘备', '40', 10000],
      //   ['关羽', '39', 9000],
      //   ['张飞', '38', 8000]
      // ]

      excel.export_json_to_excel({
        // 表头 必填
        header,
        // 表头对应的具体数据 必填
        data,
        filename: '员工信息表', // 导出下载的文件名称
        autoWidth: true, // 导出excel列宽度是否自适应
        bookType: 'xlsx' // 导出生成的文件类型
      })
    },
    // 把传入的对象形式的数据转换成二维数组
    transformExcelData (list, headers) {
      const parentArray = [] // 外层数组
      list.forEach(item => {
        // item员工信息对象
        const childArray = [] // 内层数组
        for (const key in item) { // 遍历对象
          if (headers.includes(key)) {
            if (key === 'formOfEmployment') { // 如果对象的key中有formOfEmployment
              childArray.push(this.formatEmployment(item[key]))
            } else {
              childArray.push(item[key]) // 把对象的值push进子数组中
            }
          }
        }
        parentArray.push(childArray) // 把子数组push到父数组
      })
      return parentArray
    }
  }

}
</script>

<style lang="scss" scoped>
.staff {
  width: 80px;
  height: 80px;
  border-radius: 50%;
}
</style>
